function uuid() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

import utils from "./utils";

Component({
  mixins: [],
  data: {
    id: "",
  },
  props: {
    width: 0,
    height: 0,
    nick: "",
    list: [],
  },
  didMount() {
    this.setData({
      id: uuid(),
    });

    this.props.refctx && this.props.refctx(this);
  },
  didUpdate() {},
  didUnmount() {},
  methods: {
    onLoad() {
      // let idx = this.idx || 0;
      // idx++;
      //
      // this.idx = idx;
      //
      // let totalList = this.props.list.filter(item => {
      //   return item.isImg;
      // });
      //
      // if (idx == totalList.length) {
      //   this.initCanvas();
      // }
      // eslint-disable-next-line no-undef
      this.ctx = my.createCanvasContext(this.data.id);
    },
    initCanvas(option) {
      // eslint-disable-next-line no-undef
      let ctx = this.ctx;

      let list = this.props.list;

      list.forEach(item => {
        //TODO 判断是图片还是文案

        if (item.isImg) {
          ctx.drawImage(item.url, item.left, item.top, item.width, item.height);
        } else {
          if (item.color) {
            ctx.setFillStyle(item.color);
          }

          if (item.font) {
            ctx.setFontSize(item.font);
          }

          if (item.family) {
            ctx.font = `${item.font}px abc`;
          }
          ctx.setTextAlign("left");
          if (item.center) {
            ctx.setTextAlign("center");
          }

          ctx.fillText(item.text, item.left, item.top);
        }
      });

      ctx.draw(true, () => {
        ctx.toTempFilePath({
          async success(res) {
            console.log(res, "===");
            option.success && option.success(res.filePath);
          },
          fail(e) {
            option.fail && option.fail(e);
          },
        });
      });
    },
    //生成图片链接
    async generateUrl() {
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      let _this = this;
      // eslint-disable-next-line no-undef,no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        let ctx = this.ctx;
        ctx.toTempFilePath({
          async success(res) {
            try {
              //存储到云存储
              let ctxData = await utils.uploadFile({
                filePath: res.apFilePath,
                fileType: "image",
                fileName:
                  "/" + _this.props.nick + "/shareImg/" + _this.props.nick + "_" + new Date().getTime() + ".png",
              });
              let shareUrl = ctxData.url;
              resolve(shareUrl);
              _this.props.generateurl && _this.props.generateurl(shareUrl);
            } catch (e) {
              console.log(e);
            }
          },
          fail() {
            reject();
          },
        });
      });
    },
  },
});
